﻿using Common.Cache;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace Common.Wechat
{
    /// <summary>
    /// 公众号授权
    /// </summary>
    public class MediaPlatformAuthentication
    {
        private readonly string appid, secret;
        /// <summary>
        /// 获取公众号授权token
        /// </summary>
        /// <param name="app_id"></param>
        /// <param name="app_secret"></param>
        public MediaPlatformAuthentication(string app_id, string app_secret)
        {
            this.appid = app_id;
            this.secret = app_secret;
        }
        /// <summary>
        /// 获取公众号token，已在redis缓存
        /// </summary>
        /// <returns></returns>
        public string GetAccessToken()
        {
            string key = $"accesstoken:wechat:{appid}";
            return FreeRedisCache.Instance.GetOrAdd(key, _ => GetAccessTokenFromWechat());
        }
        private JCacheEntry<string> GetAccessTokenFromWechat()
        {
            string apiUrl = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret);
            string content = HttpHelper.Get(apiUrl);
            if (string.IsNullOrEmpty(content))
            {
                return null;
            }
            var model = JsonConvert.DeserializeObject<MediaPlatformAccessToken>(content);
            if (!string.IsNullOrEmpty(model.ErrorCode) && model.ErrorCode != "0")
            {
                return null;
            }
            return new JCacheEntry<string> { Data = model.AccessToken, Expiry = model.GetExpires() };
        }
    }
    public class MediaPlatformAccessToken : MediaPlatformModelBase
    {
        [JsonProperty("access_token")]
        public string AccessToken { get; set; }
    }
}
